package com.example.consumer.consume;

import com.alibaba.fastjson.JSON;
import com.example.consumer.entity.Order;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.Argument;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/** ttl+dlx实现延时队列
 * @author shuc001
 * @Date 2018/9/27 下午4:29
 */
@Component
public class DelayConsumer2 {


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "delay_q",durable = "true"),
            exchange = @Exchange(value = "delay_ex",type = "x-delayed-message",arguments = {
                    @Argument(name = "x-delayed-type",value = "topic")
            }),
            key = "delay.#"
    ))
    @RabbitHandler
    public void receive(@Payload String json, @Headers Map<String,Object> headers, Channel channel) throws IOException {
        System.out.println("delay model x-delayed-message "+ JSON.parseObject(json,Order.class));
        channel.basicAck((Long) headers.get(AmqpHeaders.DELIVERY_TAG),true);
    }
}
